package modes;

import java.io.File;
import lejos.nxt.Sound;
import main.ColorSensorChew;
import main.Engine;
import main.SensorEngine;
import main.SonicSensor;
import navigation.Direction;
import navigation.GoRightExitNavigator;
import navigation.IllegalMapStateException;
import navigation.IllegalMoveException;
import navigation.Navigator;

/**
 * If Chewie dedicated a deadend
 * @author Max
 */
public class ModeDeadEnd extends AMode
{

    /**
     * Creates a deadend mode
     * @param cs Engine
     * @param se SensorEngine
     * @param cs ColorSensor
     * @param ss SonicSensor
     * @param navi Navigator
     */
    public ModeDeadEnd(Engine en, SensorEngine se, ColorSensorChew cs, SonicSensor ss, Navigator navi)
    {
        super(en, se, cs, ss, navi);
    }

    /**
     * Chewie turns around and tells the navigator that a deadend has been found.
     * If the deadend is at the border of the map, Chewie will recogninze this as an exit
     *
     * @return Mode den er als nächstes ausführen soll
     * @throws InterruptedException
     */
    public Mode run()
            throws InterruptedException
    {
        Mode mode = Mode.DEAD_END;
        ModeController.dm.echo("DeadEnd");
        rotationSensor.rotateMiddle();

        mode = Mode.BLACK;
        try
        {
            navi.moveOneStep();
        } catch (IllegalMoveException ex)
        {
            ModeController.dm.echo(ex.toString());
        }
        if (!navi.fieldIsKnown())
        {
            Sound.playSample(new File("chewy1.wav"), 100);
            navi.deadEndFound();
        }
        mode = reachEnd(mode);
        return mode;
    }

    private void turn()
            throws InterruptedException
    {
        //Thread.sleep(1000);
        engine.setSpeed(600);
        engine.rotateRight();
        do
        {
            color.readColor();
        } while (!color.isColorWhite());
        do
        {
            color.readColor();
        } while (color.isColorWhite());
        engine.stop();
    }

    private Mode reachEnd(Mode mode) throws InterruptedException
    {
        try
        {
            if (navi.decideDirection() == -1)
            {
                mode = Mode.END;
            } else
            {
                turn();
                navi.directionChanged(Direction.BACKWARD);
            }
        } catch (IllegalMapStateException ex)
        {
            navi = new GoRightExitNavigator(navi);

        }
        return mode;
    }
}
